import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:url_launcher/url_launcher.dart';
import 'CartOrder.dart';
import 'LjgmOrder.dart';

class ZitiListPage extends StatefulWidget {
  int type;//下订单页面跳转 1：立即购买页面  2：购物车结算页面
  String gid;//商品ID或者购物车ID集合
  int peisong;//配送方式 0：自提  1：快递
  String names;//规格
  String params;//规格下标
  double money;//选定规格金额
  int num;//数量
  double allMoney;//总金额
  String orRemark;//订单备注
  ZitiListPage({Key key, this.title, this.type, this.gid, this.peisong, this.names, this.params, this.money, this.num,this.allMoney,this.orRemark}) : super(key: key);

  final String title;

  @override
  _ZitiListPage createState() => _ZitiListPage(type,gid,peisong,names,params,money,num,allMoney,orRemark);
}

class _ZitiListPage extends State<ZitiListPage> {
  List zitis=[];
  int page=1;
  int type;
  String gid;
  int peisong;
  String names;//规格
  String params;//规格下标
  double money;//选定规格金额
  int num;//数量
  double allMoney;//总金额
  String orRemark;//订单备注

  // 构造函数
  _ZitiListPage(type,gid,peisong,names,params,money,num,allMoney,orRemark){
    this.type = type;
    this.gid = gid;
    this.peisong = peisong;
    this.names = names;
    this.params = params;
    this.money = money;
    this.num = num;
    this.allMoney = allMoney;
    this.orRemark = orRemark;
    _onLoading();
  }
  // 上拉加载控制器
  RefreshController _refreshController = RefreshController(initialRefresh: false);
  // 刷新时调用
  void _onRefresh() async{
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
  }
  // 加载数据的函数
  void _onLoading() async{
    // monitor network fetch
    // await Future.delayed(Duration(milliseconds: 1000));
    // Response response = await Dio().get("http://xllm.szghrj.com:8082/app/goods/searchAllGoods?limit=10&page=${page}");
    // var x = json.decode(response.toString());
    var x = await HttpUtil().get("/app/zitidian/searchAllZitidian?limit=10&page=${page}&key=");
    page++;
    if(x['code']==200){
      zitis.addAll(x['data']);
    }
    if(x['data'].length<1){
      _refreshController.loadNoData();
      return;
    }
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    if(mounted){
      setState(() {});
      _refreshController.loadComplete();
    }
  }

  GestureDetector _showGoods(item){
    return GestureDetector(
      child: Container(
          child: Row(
            children: [
              // Image.network("http://xllm.szghrj.com:8082${item['gimages']}",width: 70,height: 70,),
              CachedNetworkImage(imageUrl: Config.getInstance().getHost()+"images/zitidianLogo/"+item['logo'],width:ScreenUtil().setWidth(80) ,height: ScreenUtil().setHeight(80),),
              Container(
                child: Column(
                children: [
                  Text(item['zitiName']),
                  Text(item['zitiDetail']),
                  GestureDetector(child:Text("联系电话:${item['phone']}"),onTap: () async{
                    if( await canLaunch("tel:"+item['phone'])){
                      await launch("tel:"+item['phone']);
                    }else{
                      throw "拨号失败"; // 模拟器会失败，真机可以拨号
                    }
                  },)

                ],),
              ),
            ],
          ),
      ),
      onTap: (){
        String id = item['zitiId'];//自提地址ID
        if(type == 1){
          MyRoute.push(LjgmOrder(adId:id,gid:gid,peisong:peisong,num: num,names: names,params: params,money: money,allMoney: allMoney,orRemark: orRemark,));//跳立即购买页面
          // MyRoute.push(LjgmOrder(adId:id,gid:gid,peisong:peisong));//跳立即购买页面
          return;
        }else if(type == 2){
          MyRoute.push(CartOrder(adId:id,catid:gid,orRemark: orRemark,));//跳购物车结算页面
          return;
        }
        // Navigator.push(
        //     context,
        //     MaterialPageRoute(
        //         builder:(context)=>ZitiDetailPage(ztid:item['zitiId']),
        //     )
        // );
      },
    );

  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context , width: 464 , height: 820) ;
    return Scaffold(
      appBar: AppBar(
        title: Text("自提点列表"),
      ),
      body: SmartRefresher(
        enablePullDown: false,
        enablePullUp: true,
        header: WaterDropHeader(),
        footer: CustomFooter(
          builder: (BuildContext context,LoadStatus mode){
            Widget body ;
            if(mode==LoadStatus.idle){
              body =  Text("上拉加载");
            }
            else if(mode==LoadStatus.loading){
              body =  CupertinoActivityIndicator();
            }
            else if(mode == LoadStatus.failed){
              body = Text("加载失败！点击重试！");
            }
            else if(mode == LoadStatus.canLoading){
              body = Text("松手,加载更多!");
            }
            else{
              body = Text("没有更多数据了!");
            }
            return Container(
              height: 55.0,
              child: Center(child:body),
            );
          },
        ),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: ListView.builder(
          itemBuilder: (c, i) => Card(child: _showGoods(zitis[i])),
          itemExtent: 100.0,
          itemCount: zitis.length,
        ),
      ),
    );
  }
}